package org.example.dao;

import org.example.model.book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


@Repository
public class BookDaoImp implements BookDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean isExistById(String id) {
        String sql = "select count(*) from book where id=?";
        return jdbcTemplate.queryForObject(sql, Integer.class, id) > 0;
    }

    @Override
    public int insert(book book) {
        String sql = "insert into book(id,name,author,publisher,price) values (?,?,?,?,?)";
        return jdbcTemplate.update(
                sql,
                book.getId(),
                book.getName(),
                book.getAuthor(),
                book.getPublisher(),
                book.getPrice());

    }

    @Override
    public int delete(String id) {
        String sql = "delete from book where id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @Override
    public int deleteAll() {
        String sql = "delete from book";
        return jdbcTemplate.update(sql);
    }

    @Override
    public int update(book book) {
        String sql = "update book set name=?,author=?,publisher=?,price=?where id=?";
        return jdbcTemplate.update(sql, book.getName(), book.getAuthor(),
                book.getPublisher(), book.getPrice(), book.getId()
        );
    }

    @Override
    public book queryById(String id) {
        id = id.replaceAll(".*([';]+|(--)+).*", " ");
        String sql = "select id,name,author,publisher,price from book where id = '" + id + "'";
        List<book> bookList = jdbcTemplate.query(sql, this::transform);
        if (bookList.isEmpty()) return null;
        else return bookList.get(0);
    }

    @Override
    public List<book> queryByName(String name) {
        name = name.replaceAll(".*([';]+|(--)+).*", " ");
        String sql = "select id,name,author,publisher,price from book where name= '" + name + "'";
        return jdbcTemplate.query(sql, this::transform);
    }

    @Override
    public List<book> queryAll() {
        String sql = "select id,name,author,publisher,price from book ";
        return jdbcTemplate.query(sql, this::transform);
    }

    private book transform(ResultSet rs, int rowNum) throws SQLException {
        //* 当前行映射到对应 User 对象*//
        book book = new book();
        book.setId(rs.getString("id"));
        book.setName(rs.getString("name"));
        book.setAuthor(rs.getString("author"));
        book.setPublisher(rs.getString("publisher"));
        book.setPrice(Double.parseDouble(rs.getString("price")));
        return book;
    }
}
